<template>
  <div >
    <div v-if="isSubmitting" class="overlay" ></div>
	<!-- 添加上传按钮 -->
	<div >
		<div v-if="subProjectstatus === '报价中' && (userRole.includes('分包商') || userRole.includes('admin')) " style="width: 100%;">
			<j-upload  @success="handleUploadSuccess" text="导入" fileType="image"  ></j-upload>
		</div>
		<div v-if="subProjectstatus === '报价中' && (userRole.includes('分包商') || userRole.includes('admin'))" style="width: 100%;">
		  <a-button block class="mt-5" type="dashed" @click="handleAdd" style="background-color: #038ffb;width: 10% "> 添加任务 </a-button>
		  <a-button block class="mt-5" type="dashed" @click="submitReview" style="background-color: #fdd106 ;width: 10% "> 提交审核 </a-button>
		</div>
		
		<div v-if="subProjectstatus === '审核中' && (userRole.includes('项目经理') || userRole.includes('admin'))" style="width: 100%;">
		  <a-button block class="mt-5" type="dashed" @click="showAuditModal('同意')" style="background-color: #038ffb;width: 10%"> 同意 </a-button>
		  <a-button block class="mt-5" type="dashed" @click="showAuditModal('驳回')" style="background-color: #f5381d;width: 10%"> 驳回 </a-button>
		</div>
		
		<div v-if="subProjectstatus === '施工中' && (userRole.includes('项目经理') || userRole.includes('admin'))" style="width: 100%;">
		  <a-button block class="mt-5" type="dashed" @click="showAuditModal('维保中')" style="background-color: #f5381d;width: 10%"> 维保中 </a-button>
		</div>
		<div v-if="subProjectstatus === '维保中' && (userRole.includes('项目经理') || userRole.includes('admin'))" style="width: 100%;">
		  <a-button block class="mt-5" type="dashed" @click="showAuditModal('完成')" style="background-color: #f5381d;width: 10%"> 完成 </a-button>
		</div>
	</div>
    <BasicTable @register="registerTable" @edit-change="handleEditChange"   >
      <template #action="{ record, column }">
        <div v-if="subProjectstatus === '报价中' && userRole.includes('分包商')">
          <TableAction :actions="createActions(record, column)" />
        </div>
      </template>
      <template #bodyCell="{ column, record }">
       <!-- <template v-if="column.dataIndex === 'taskName'">
			<a-input v-model:value="record.taskName" allow-clear></a-input>
        </template> -->
      </template>
    </BasicTable>
	
    
      
	

    <a-modal
      v-model:open="isAuditModalVisible"
      title="审核"
      @ok="handleAudit"
      @cancel="isAuditModalVisible = false"
      class="audit-modal-wrap"
    >

      <a-form :model="auditForm" layout="vertical">
        <a-input v-model:value="auditForm.status" :readonly="true" placeholder="请输入状态" :rows="4" />
        <a-form-item label="驳回原因" v-if="auditForm.status === '驳回'">
          <a-textarea v-model:value="auditForm.remark" placeholder="请输入驳回原因" :rows="4" />
        </a-form-item>
        <a-form-item label="备注" v-if="auditForm.status === '同意'">
          <a-textarea v-model:value="auditForm.remark" placeholder="请输入备注" :rows="4" />
        </a-form-item>
        <a-form-item label="备注" v-if="auditForm.status === '维保中'">
          <a-textarea v-model:value="auditForm.remark" placeholder="请输入备注" :rows="4" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref, } from 'vue';
import { BasicTable, useTable, TableAction, BasicColumn, ActionItem, EditRecordRow } from '/@/components/Table';
import { Select, Modal, Form, Input, Radio, Textarea, DatePicker, Button } from 'ant-design-vue';
import { getContractorInfoList, getMaterialList, postSubmitReview, getSubProjectInfo,
 getSubProjectTask, postAuditSubProject,getOcrAssistant } from './orderInfo.api';
import { useRoute } from 'vue-router';
import { useMessage } from '/@/hooks/web/useMessage';
import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
import { mapTableTotalSummary } from '/@/utils/common/compUtils';

const columns: BasicColumn[] = [
  {
    title: '名称',
    dataIndex: 'taskName',
    editRow: true,
  },
  {
    title: '品牌',
    dataIndex: 'brand',
    editRow: true,
  },
  {
    title: '型号',
    dataIndex: 'model',
    editRow: true,
  },
  {
    title: '数量',
    dataIndex: 'quantity',
    editRow: true,
  },
  {
    title: '单位',
    dataIndex: 'unit',
    editRow: true,
  },
{
    title: '主材',
    dataIndex: 'mainPrice',
    editRow: true,
  },
  {
    title: '辅材',
    dataIndex: 'auxiliaryPrice',
    editRow: true,
  },
  {
    title: '人工',
    dataIndex: 'laborPrice',
    editRow: true,
  },
  {
    title: '总价',
    dataIndex: 'totalContractor',
    editRow: true,
  },
  {
    title: '备注',
    dataIndex: 'remark',
    editRow: true,
  },
];

const orderInfoData = ref();
// 控制遮罩层显示的变量
const isSubmitting = ref(false);

//子项目状态
const subProjectstatus = ref('');
const userRole = ref(''); //角色
const isAuditModalVisible = ref(false);
const auditForm = ref({
  status: '', // 'approved' or 'rejected'
  remark: '',
});

// Remove `let data: any[] = [];` from here
// Instead, manage table data directly through useTable's `setTableData` or a ref within setup.




export default defineComponent({
  props: {
    subProjectId: {
      type: String,
      required: true,
    },
  },
  components: {
    BasicTable,
    TableAction,
    'a-select': Select,
    'a-modal': Modal,
    'a-form': Form,
    'a-form-item': Form.Item,
    'a-input': Input,
    'a-radio-group': Radio.Group,
    'a-radio': Radio,
    'a-textarea': Textarea,
    'a-range-picker': DatePicker.RangePicker,
    'a-button': Button,
	JUpload, // 引入 JUpload 组件
  },
  setup(props) {
    const { createMessage } = useMessage();
    const { subProjectId } = props;
    // Initialize data as an empty array here, or let useTable manage it
    const [registerTable, { getDataSource, setTableData }] = useTable({ // Add setTableData
      columns: columns,
      showIndexColumn: true,
      dataSource: [], // Start with an empty array
      actionColumn: {
        width: 160,
        title: '操作',
        dataIndex: 'action',
        slots: { customRender: 'action' },
      },
      pagination: false,
	  // 显示底部合计
	  showSummary: true,
	  // 底部合计计算方法
	  summaryFunc: onSummary,
    });
	function onSummary(tableData: Recordable[]) {
	  // 可用工具方法自动计算合计
	  const totals = mapTableTotalSummary(tableData, ['totalContractor']);
	  return [
	    totals,
	    {
        _row: '不含税合计',
        _index: '不含税合计',
	     totalContractor: totals.totalContractor.toFixed(2),
	    },
	  ];
	}

   

    function handleEdit(record: EditRecordRow) {
      record.editable = true;
      record.onEdit?.(true);
    }

    function handleCancel(record: EditRecordRow) {
      record.editable = false;
      record.onEdit?.(false);
      if (record.isNew) {
        // Use setTableData to update the source array
        setTableData(getDataSource().filter((item: EditRecordRow) => item.key !== record.key));
      }
    }

    function handleSave(record: EditRecordRow) {
      record.editable = false;
      record.onEdit?.(false, true);
    }

    function handleEditChange(data: Recordable) {
      console.log(data);
    }


    async function subProjectInfo() {
      try {
        const params = { id: subProjectId };
        const result = await getSubProjectInfo(params);
        subProjectstatus.value = result.status;
        userRole.value = result.userRole;
      } catch (error) {
        console.error('获取子项目信息失败:', error);
      }
    }

    async function subProjectTask() {
      try {
        // Clear existing data before fetching new data
        setTableData([]);
        const params = { subProjectId: subProjectId };
        const result = await getSubProjectTask(params);
        // Set the fetched data to the table
        setTableData(result);
      } catch (error) {
        console.error('查询任务记录失败:', error);
      }
    }

    function handleAdd() {
      const currentData = getDataSource(); // Get current data
      const addRow: EditRecordRow = {
        taskName: '',
		brand:'',
		model:'',
        quantity: '',
        unit: '',
        mainPrice: '',
        auxiliaryPrice: '',
        laborPrice: '',
        totalContractor: '',
        remark: '',
        editable: true,
        isNew: true,
        key: `${Date.now()}`,
      };
      setTableData([...currentData, addRow]); // Add new row and update table data
    }

    function createActions(record: EditRecordRow, column: BasicColumn): ActionItem[] {
      if (!record.editable) {
        return [
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
          },
          {
            label: '删除',
            // You might want to implement a delete function here
             onClick: handleDelete.bind(null, record), // Add delete functionality
          },
        ];
      }
      return [
        {
          label: '保存',
          onClick: handleSave.bind(null, record, column),
        },
        {
          label: '取消',
          popConfirm: {
            title: '是否取消编辑',
            confirm: handleCancel.bind(null, record, column),
          },
        },
      ];
    }

    function handleDelete(record: EditRecordRow) {
      // Implement your delete logic here, likely calling an API and then updating the table
      setTableData(getDataSource().filter((item: EditRecordRow) => item.key !== record.key));
      createMessage.success('任务已删除');
    }

    async function submitReview() {
      isSubmitting.value = true;
      const recordList = getDataSource();
      for (let i = 0; i < recordList.length; i++) {
        const record = recordList[i];
        if (record.editable) {
          createMessage.error('提交失败,请先保存所有报价！');
          isSubmitting.value = false;
          return;
        }
      }

      const submitReviewList = recordList.map((item: any) => ({
        taskName: item.taskName,
		brand: item.brand,
		model: item.model,
        quantity: item.quantity,
        unit: item.unit,
        mainPrice: item.mainPrice,
        auxiliaryPrice: item.auxiliaryPrice,
        laborPrice: item.laborPrice,
		totalContractor: item.totalContractor,
		remark: item.remark,
      }));

      const auditParametersDTO = {
        subProjectId: subProjectId,
        submitReviewDTOList: submitReviewList,
      };

      try {
        await postSubmitReview(auditParametersDTO);
        createMessage.success('提交审核成功');
        window.location.reload();
      } catch (error) {
        createMessage.error('提交审核失败');
        console.error('提交审核失败:', error);
      } finally {
        isSubmitting.value = false;
      }
    }

    function showAuditModal(status: string) {
      auditForm.value.status = status;
      auditForm.value.remark = '';
      isAuditModalVisible.value = true;
    }

    async function handleAudit() {
      isSubmitting.value = true;
      try {
        const params = {
          subProjectId: subProjectId,
          remark: auditForm.value.remark,
          status: auditForm.value.status,
        };
        await postAuditSubProject(params);
        createMessage.success(`子项目已${auditForm.value.status === '同意' ? '同意' : auditForm.value.status === '驳回' ? '驳回' : auditForm.value.status}`);
        isAuditModalVisible.value = false;
        window.location.reload();
      } catch (error) {
        createMessage.error('操作失败');
        console.error('审核操作失败:', error);
      } finally {
        isSubmitting.value = false;
      }
    }
	const dynamicHeight = ref('800px'); // 默认值
    onMounted(() => {
      subProjectInfo();
      subProjectTask();
    });
	


	
	 // 上传成功回调
	async function handleUploadSuccess(response: any, file: any) {
		debugger
	    
		 try{
			 const param = {'filePath':response.message}
			 const result = await getOcrAssistant(param);
			 if (result && result.length > 0) {
			       const currentData = getDataSource(); // 获取当前表格数据
			       const newRows: EditRecordRow[] = result.map((item: any) => ({
			         taskName: item.名称 || '', 
					 brand: '',
					 model: '',
			         quantity: item.数量 || '', 
			         unit: item.单位 || '', 
			         mainPrice: item.主材 || '', 
			         auxiliaryPrice: item.辅材 || '', 
			         laborPrice: item.人工 || '', 
			         totalContractor: item.总计 || '', 
			         remark: item.备注 || '',
			         editable: true,
			         isNew: true,
			         key: `${Date.now()}`,
			       }));
			       setTableData([...currentData, ...newRows]); // 添加新行并更新表格数据
			     } else {
			       createMessage.error('OCR 识别结果为空');
			     }
			sourceValue.value = source;
			emit('change', source, data);
			createMessage.success(t('component.cropper.uploadSuccess'));
		 }catch (error) {
			createMessage.error('识别失败');
			console.error('识别失败:', error);
		  } 
		
	}
	    // 上传失败回调
	    function handleUploadError(error: any, file: any) {
	      createMessage.error(`文件上传失败: ${file.name}`);
	      console.error('上传失败:', error);
	    }
    return {
      registerTable,
      handleEdit,
      createActions,
      handleAdd,
      getDataSource,
      handleEditChange,
      onMounted,
      submitReview,
      useRoute,
      subProjectId,
      isSubmitting,
      subProjectstatus,
      userRole,
      isAuditModalVisible,
      auditForm,
      showAuditModal,
      handleAudit,
	handleUploadSuccess,
	  handleUploadError,
	
    };
  },
});
</script>

<style scoped>
.overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1000;
}
.audit-modal-wrap :deep(.ant-modal-body) {
  padding: 24px 32px;
}
</style>